package com.txm.qqserver.service;

import com.txm.qqcommon.Message;
import com.txm.qqcommon.MessageType;
import com.txm.qqcommon.Response;
import com.txm.qqcommon.User;
import com.txm.qqdatabase.DB;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Comparator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;

public class UserServerService extends QQServer {

    public UserServerService() {
        super();
    }

    public static User checkUser(User user) {
//      判断账号和密码是否合法
//        System.out.println("login:" + user);
        ConcurrentHashMap<String, User> users = DB.users;
        User user_ = null;
        Collection<User> values = users.values();
        for (User val : values) {
            if (val.getUsername().equals(user.getUsername()) && val.getPassword().equals(user.getPassword())) {
                user_ = val;
                break;
            }
        }
        return user_;
    }

    public void login(Object obj) {
        try {
            User res = (User) obj;
            //输出流
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(getAccept().getOutputStream());
            //查看线程中是否存在当前用户，有则提示已在其他设备登录
            ServerConnectServerThread contains = null;
            if ((contains = getMCTC().isInThreads(((User) getRes().getObject()).getUsername())) != null) {
                System.out.println("contains" + contains);
                contains.msgContent = "当前账号在其他设备上登录，服务即将结束。";
                contains.isLive = false;
                ObjectOutputStream oos = new ObjectOutputStream(contains.accept.getOutputStream());
                Message message = new Message();
                message.setCurrentLocalDate();
                message.setGetter(contains.user.getUserId());
                message.setMsgType(MessageType.MESSAGE_SYSTEM_EXIT);
                message.setContent(contains.msgContent);
                message.setObject(contains.user);
                oos.writeObject(message);
            }
            User user;
            if ((user = checkUser(res)) != null) {
                objectOutputStream.writeObject(new Message(null, res.getUsername(), "登录成功", null, MessageType.MESSAGE_LOGIN_SUCCEED, user));
                ServerConnectServerThread serverConnectServerThread = new ServerConnectServerThread(getAccept(), user);
                serverConnectServerThread.setName(user.getUsername()+" "+Message.getLocalDate());
                serverConnectServerThread.start();
                ManageClientThreads.setMcts(user.getUserId(), serverConnectServerThread);
            } else {
                objectOutputStream.writeObject(new Message(null, res.getUsername(), "账号与密码不相匹配，请重新输入。", null, MessageType.MESSAGE_LOGIN_FAIL, user));
                getAccept().close();
            }
        } catch (Exception e) {
            System.out.println("Exception：" + e);
        }
    }

    public static void getOnlineUsers(Object obj, ServerConnectServerThread scst) {

        try {
            Response res = (Response) obj;
            if (!res.getPath().equals("/getOnlineUsers")) return;
//            System.out.println("res：" + res);
            handleUserThread(scst);
        } catch (Exception e) {
            System.out.println("UserServerService Exception：" + e);
            e.printStackTrace();
        }
    }

    public static void handleUserThread(ServerConnectServerThread scst) {
        ConcurrentHashMap<String, User> users = new ConcurrentHashMap<>(DB.users);
        users.remove(scst.user.getUserId());
        StringBuffer str = new StringBuffer();
        Collection<User> values = users.values();
        Stream<User> sorted = values.stream().sorted(Comparator.comparing(User::getUserId));

//            System.out.println("M" + ManageClientThreads.getMcts()+"\n"+users);
        sorted.forEach((User val) -> {
            if (ManageClientThreads.getMcts().containsKey(val.getUserId())) {
                str.append("\n").append(val.getUserId()).append(":").append(val.getUsername());
            }
        });

        Message message = new Message();
        message.setCurrentLocalDate();
        message.setContent(str.toString().isEmpty() ? "当前无用户在线" : str.toString());
        message.setMsgType(MessageType.MESSAGE_GET_ONLINE_USER);
        message.setGetter(scst.user.getUserId());
        try {
            ObjectOutputStream oOStream = new ObjectOutputStream(scst.accept.getOutputStream());
            oOStream.writeObject(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void method(String path, Object obj) {
//        System.out.println(path + "\t" + obj);
        if (path.isEmpty()) return;
        if (path.equals("/login")) {
            login(obj);
        }
    }
}
